package com.example;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.time.Duration;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VideoTest {

    @Test
    public void testRegex() {
        String script = "\"videoInfo\": {\n" +
                "          \"size\": 32304827,\n" +
                "          \"image\": 'https://n.sinaimg.cn/sinakd20210727ac/400/w1280h720/20210727/6d3b-198e01766e255ef32d6b98472e17ea61.jpg',\n" +
                "          \"playUrl\": 'https://edge.ivideo.sina.com.cn/40861857402.mp4?KID=sina,viask&amp;Expires=1627574400&amp;ssig=d%2BQ1fZVI2Y&amp;reqid=&amp;r=video.sina.com.cn%2Fview%2F408618574.html',\n" +
                "          \"videoId\": '408618574',\n" +
                "          \"timeLength\": 351,\n" +
                "          \"livesource\": 'vms', //  ?\n" +
                "          \"vid\": \"\", //  ?\n" +
                "          \"editchannel\": 'news' //  ?\n" +
                "        }";
        String regex1 = "https\\:\\/\\/edge\\.ivideo\\.sina\\.com\\.cn[\\s\\S]*\\.html";
        String regex2 = "https\\:\\/\\/edge\\.ivideo\\.sina\\.com\\.cn(.*)\\.html";
        Pattern p = Pattern.compile(regex2);
        Matcher matcher = p.matcher(script);
        System.out.println(matcher.find());
        System.out.println(matcher.groupCount());
        System.out.println(matcher.group());
    }

    @Test
    public void testDownload() {
        String playUrl = "https://edge.ivideo.sina.com.cn/40861857402.mp4?KID=sina,viask&Expires=1627488000&ssig=RMgbJqlZqw&reqid=&r=video.sina.com.cn%2Fview%2F408618574.html";
        try {
            URL target = new URL(playUrl);
            URLConnection connection = target.openConnection();
            String name = "test3.mp4";
            // 本地路径
            String localPath = System.getProperty("user.dir") + "\\video\\" + name;
            // 构造输入流、输出流
            try(InputStream is = connection.getInputStream();
                FileOutputStream fos = new FileOutputStream(localPath)) {
                byte[] buffer = new byte[4 * 1024];
                int len;
                while ((len = is.read(buffer)) != -1) { // 读
                    fos.write(buffer, 0, len);      // 写
                }
                System.out.println("下载完成：");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testParsePage() {
        String regex = "https\\:\\/\\/edge\\.ivideo\\.sina\\.com\\.cn(.*)\\.html";
        Pattern p = Pattern.compile(regex);
        try {
            // 1.解析页面
            Document document = Jsoup.connect("https://k.sina.cn/article_2748597475_ma3d444e3020015muq.html?from=news&subch=onews").get();
            Elements script = document.getElementsByTag("script");
            for (Element s : script) {
                // 2.匹配视频地址
                Matcher matcher = p.matcher(s.html());
                if (matcher.find()) {
                    String playUrl = matcher.group();
                    // 3.视频地址解码
                    System.out.println(playUrl);
                    playUrl = Parser.unescapeEntities(playUrl, true);
                    System.out.println(playUrl);
                    // 4.下载视频
                    URL target = new URL(playUrl);
                    URLConnection connection = target.openConnection();
                    String name = UUID.randomUUID().toString().replace("-", "") + ".mp4";
                    // 本地路径
                    String localPath = System.getProperty("user.dir") + "\\video\\" + name;
                    System.out.println("开始下载");
                    LocalTime start = LocalTime.now();
                    try(InputStream is = connection.getInputStream();
                        FileOutputStream fos = new FileOutputStream(localPath)) {
                        byte[] buffer = new byte[1024 * 4];
                        int len;
                        while ((len = is.read(buffer)) != -1) { // 读
                            fos.write(buffer, 0, len);      // 写
                        }
                    } catch (IOException e) {
                        System.out.println("下载失败");
                        e.printStackTrace();
                    }
                    LocalTime end = LocalTime.now();
                    Duration duration = Duration.between(start, end);
                    System.out.println("下载完成，用时" + duration.toSeconds() + "秒");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testParseList() {
        try {
            // 1.解析页面
            Document document = Jsoup.connect("https://sapi.sina.cn/search/list?newsId=HB-1-snhs%2Findex_v2-search&page=1&newspage=0&keyword=%25E7%25A2%25B3&tab=shortVideo&sort=0&is_ec=0").get();
            Element body = document.body();
            String json = body.text();

            ObjectMapper mapper = new ObjectMapper();
            Map map = mapper.readValue(json, Map.class);
            Map data = (Map) map.get("data");
            List<Map<String, String>> feed = (List) data.get("feed");

            for (Map<String, String> item : feed) {
                // 标题
                String title = item.get("title");
                System.out.println(title);
                // 资讯链接
                String link = item.get("link");
                // 解析资讯详情
                String regex = "https\\:\\/\\/edge\\.ivideo\\.sina\\.com\\.cn(.*)\\.html";
                Pattern p = Pattern.compile(regex);
                try {
                    // 1.解析页面
                    Document document2 = Jsoup.connect(link).get();
                    Elements script = document2.getElementsByTag("script");
                    for (Element s : script) {
                        // 2.匹配视频地址
                        Matcher matcher = p.matcher(s.html());
                        if (matcher.find()) {
                            String playUrl = matcher.group();
                            // 3.视频地址解码
                            playUrl = Parser.unescapeEntities(playUrl, true);
                            System.out.println(playUrl);
                            // 4.下载视频
                            URL target = new URL(playUrl);
                            URLConnection connection = target.openConnection();
                            String name = UUID.randomUUID().toString().replace("-", "") + ".mp4";
                            // 本地路径
                            String localPath = System.getProperty("user.dir") + "\\video\\" + name;
                            System.out.println("开始下载");
                            LocalTime start = LocalTime.now();
                            try(InputStream is = connection.getInputStream();
                                FileOutputStream fos = new FileOutputStream(localPath)) {
                                byte[] buffer = new byte[1024 * 4];
                                int len;
                                while ((len = is.read(buffer)) != -1) { // 读
                                    fos.write(buffer, 0, len);      // 写
                                }
                            } catch (IOException e) {
                                System.out.println("下载失败");
                                e.printStackTrace();
                            }
                            LocalTime end = LocalTime.now();
                            Duration duration = Duration.between(start, end);
                            System.out.println("下载完成，用时" + duration.toSeconds() + "秒");
                            System.out.println("=========================================");
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
